import { storeBindingsBehavior } from 'mobx-miniprogram-bindings'
import { store } from '@/utils/store'
import { call } from '@/utils/request'
import { showMsg, showLoading, hideLoading, showSuccess, showBookError } from '@/utils/toast'

const page_size = 10
let last_id
let isLoading
Component({
  behaviors: [storeBindingsBehavior],
  data: {
    orderList: [],
    isRefreshPull: false,
    isFinish: false,
    isEmpty: false,
    timer_count_down: null,
    pauseTime: 0,
  },
  storeBindings: {
    store,
    fields: ['window_info', 'config'],
  },
  lifetimes: {
    // 注意：在下面这两个方法里无法访问上面的局部变量，所以timer必须放在data里！！！！！！！！！！！！！
    attached() {
      this.data.timer_count_down = setInterval(() => {
        let is_render = false
        const {
          orderList,
          config: { UN_PAY, CANCEL },
        } = this.data
        orderList.forEach(item => {
          if (item.status === UN_PAY) {
            is_render = true
            if (item.pay_leave_seconds <= 1) {
              item.status = CANCEL
              this.getStatusChineseAndClass(item)
            } else {
              item.pay_leave_seconds--
            }
          }
        })
        if (is_render) {
          this.setData({
            orderList: orderList,
          })
        }
      }, 1000)
    },
    detached() {
      clearInterval(this.data.timer_count_down)
    },
  },
  pageLifetimes: {
    show() {
      const { pauseTime, orderList, config } = this.data
      if (pauseTime === 0) return
      const diff = Math.ceil((Date.now() - pauseTime) / 1000)
      let is_render = false
      orderList.forEach(item => {
        if (item.status === config.UN_PAY) {
          is_render = true
          if (item.pay_leave_seconds - diff <= 0) {
            item.status = config.CANCEL
            this.getStatusChineseAndClass(item)
          } else {
            item.pay_leave_seconds -= diff
          }
        }
      })

      this.data.pauseTime = 0
      if (is_render) {
        this.setData({
          orderList: orderList,
        })
      }
    },
    hide() {
      this.setData({ pauseTime: Date.now() })
    },
  },
  methods: {
    async init() {
      // 一定要初始化普通变量，原因：这些变量永远不会销毁，值永远也不会改变！！！！！！！！！！！！！！！！！
      last_id = 2147483647
      isLoading = false

      showLoading()
      const orderList = await this.getOrderBookPage()
      this.setData({
        orderList: orderList,
        isEmpty: orderList.length === 0 ? true : false,
        isRefreshPull: false,
      })
      hideLoading()
    },
    // onCountDownFinish(id) {
    //   console.log(id);
    //   this.changeStatus(id, this.data.config.CANCEL)
    // },
    async getOrderBookPage() {
      const res = await call('/getOrderBookListAll/' + last_id + '/' + page_size)

      if (res.length < page_size) {
        this.setData({
          isFinish: true,
        })
      } else {
        this.setData({
          isFinish: false,
        })
      }

      if (res.length > 0) {
        last_id = res[res.length - 1].id
        res.forEach(item => {
          const t1 = item.book_start_time
          const t2 = item.book_end_time
          item.time_str =
            (t1 < 10 ? '0' + t1 : '' + t1) + ':00~' + (t2 < 10 ? '0' + t2 : '' + t2) + ':00'

          this.getStatusChineseAndClass(item)
        })
      }

      return res
    },
    getStatusChineseAndClass(item) {
      const { UN_PAY, PAID, ACTIVITY_SUCCESS, CANCEL, APPLY_REFUND, REFUND_ERROR, RECEIVED_REFUND } = this.data.config
      switch (item.status) {
        case UN_PAY:
          item.status_str = '待支付'
          item.status_class = 'unpay'
          break
        case PAID:
          item.status_str = item.activity_id ? '活动确认中' : '预订成功'
          item.status_class = 'paid'
          break
        case ACTIVITY_SUCCESS:
          item.status_str = '报名成功'
          item.status_class = 'paid'
          break
        case CANCEL:
          item.status_str = '已取消'
          item.status_class = 'cancel'
          break
        case APPLY_REFUND:
        case REFUND_ERROR:
        case RECEIVED_REFUND:
          item.status_str = item.refund_type === 3 ? '报名失败，已退款' : '已退款'
          item.status_class = 'refund'
          break
      }
    },
    async onScrollBottom() {
      if (this.data.isFinish || isLoading) return
      isLoading = true
      showLoading()
      var res = await this.getOrderBookPage()
      res = this.data.orderList.concat(res)
      this.setData({
        orderList: res,
        isRefreshPull: false,
      })
      hideLoading()
      isLoading = false
    },
    async cancelPay({ mark: { id } }) {
      const { cancel } = await wx.showModal({
        content: '确定要取消该预订吗？',
      })
      if (cancel) return

      showLoading()
      await call('/cancelOrderBook/' + id)

      // 重新渲染
      showSuccess('取消预订成功！')
      this.changeStatus(id, this.data.config.CANCEL)
    },
    async toPay({ mark: { id, activity_id } }) {
      showLoading()
      const { out_trade_no, wx_pay_res } = await call('/payOrderBook/' + id)
      hideLoading()

      wx_pay_res.package = wx_pay_res.packageVal
      wx.requestPayment(wx_pay_res).then(() => {
        wx.showLoading({
          title: activity_id ? '正在报名活动...' : '正在预订场地...',
          mask: true,
        })
        this.paySuccess(out_trade_no, id)
      })
    },
    paySuccess(out_trade_no, id) {
      const { PAID, ACTIVITY_SUCCESS } = this.data.config
      var timer = setInterval(async () => {
        call('/getOneOrderBookById/' + id).then(res => {
          if (res.status === PAID || res.status === ACTIVITY_SUCCESS) {
            showSuccess('支付成功！')
            clearInterval(timer)
            timer = undefined
            this.changeStatus(id, PAID)
          }
        })
      }, 1000)

      setTimeout(() => {
        if (timer !== undefined) {
          call('/queryWxPayStatus/' + out_trade_no).catch(res => {
            clearInterval(timer)
            showBookError()
          })
        }
      }, 5000)
    },
    async applyRefund({ mark: { id } }) {
      const { cancel } = await wx.showModal({
        content: '确定要取消该预订吗？',
      })
      if (cancel) return

      showLoading()
      await call('/refundOrderBook/' + id)

      showSuccess('72小时内到账', 2000)
      this.changeStatus(id, this.data.config.APPLY_REFUND)
    },
    changeStatus(id, status) {
      const {
        orderList,
        config: { UN_PAY, PAID, CANCEL, APPLY_REFUND, RECEIVED_REFUND },
      } = this.data
      const index = orderList.findIndex(item => item.id === id)
      const order = orderList[index]
      order.status = status
      this.getStatusChineseAndClass(order)

      this.setData({
        [`orderList[${index}]`]: order,
      })
    },
  },
})
